/**
 * 
 */
package com.asohofrucol.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.primefaces.model.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import com.asohofrucol.dao.AgrarianResourceDao;
import com.asohofrucol.dao.AssociativityDao;
import com.asohofrucol.dao.ForestResourceDao;
import com.asohofrucol.dao.LivestockResourceDao;
import com.asohofrucol.dao.ProcessTransferInnovationDao;
import com.asohofrucol.dao.RuatDao;
import com.asohofrucol.dao.SurveyDao;
import com.asohofrucol.dto.AgrarianResourceDTO;
import com.asohofrucol.dto.AgrarianResourceRegisterDTO;
import com.asohofrucol.dto.AssociativityDTO;
import com.asohofrucol.dto.AssociativityRegisterDTO;
import com.asohofrucol.dto.ForestResourceDTO;
import com.asohofrucol.dto.ForestResourceRegisterDTO;
import com.asohofrucol.dto.LivestockResourceDTO;
import com.asohofrucol.dto.LivestockResourceRegisterDTO;
import com.asohofrucol.dto.ProcessTransferInnovationDTO;
import com.asohofrucol.dto.ProcessTransferInnovationRegisterDTO;
import com.asohofrucol.dto.RuatRegisterDTO;
import com.asohofrucol.dto.SurveyDTO;
import com.asohofrucol.dto.util.AgrarianResourceHelperDto;
import com.asohofrucol.dto.util.AssociativityHelperDto;
import com.asohofrucol.dto.util.ForestResourceHelperDto;
import com.asohofrucol.dto.util.LivestockResourceHelperDto;
import com.asohofrucol.dto.util.ProcessTransferInnovationHelperDto;
import com.asohofrucol.dto.util.RuatHelperDto;
import com.asohofrucol.dto.util.SurveyHelperDto;
import com.asohofrucol.model.AgrarianResource;
import com.asohofrucol.model.Associativity;
import com.asohofrucol.model.ForestResource;
import com.asohofrucol.model.LivestockResource;
import com.asohofrucol.model.ProcessTransferInnovation;
import com.asohofrucol.model.Ruat;
import com.asohofrucol.model.Survey;
import com.asohofrucol.service.UserOwnerService;

/**
 * @author Iván
 * 
 */
@Service("UserOwnerService")
public class UserOwnerServiceImpl implements UserOwnerService, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Autowired
	private RuatDao ruatDao;
	@Autowired
	private AssociativityDao associativityDao;
	@Autowired
	private ProcessTransferInnovationDao processTransferInnovationDao;
	@Autowired
	private AgrarianResourceDao agrarianResourceDao;
	@Autowired
	private ForestResourceDao forestResourceDao;
	@Autowired
	private LivestockResourceDao livestockResourceDao;
	@Autowired
	private SurveyDao surveyDao;
	public static String NON_VALUE = "-NoN";

	@Override
	public RuatRegisterDTO saveRuatRegisterDTO(RuatRegisterDTO ruatRegisterDTO,
			String userModifier) {
		if (null != ruatRegisterDTO && ruatRegisterDTO.getIdType() != null
				&& ruatRegisterDTO.getIdNumber() != null
				&& !ruatRegisterDTO.getIdNumber().equals("")) {
			Long idType = ruatRegisterDTO.getIdType();
			String idNumber = ruatRegisterDTO.getIdNumber();
			Ruat ruat = RuatHelperDto.converToEntity(ruatRegisterDTO);

			List<Ruat> matches = ruatDao.findByIdTypeIdNumber(idType, idNumber);
			if (matches != null && !matches.isEmpty()) {// si existe la
														// combinacion typeID y
														// IDnumber debemos
														// atualizarlo
				System.out.println("registros encontrados " + matches.size());
				ruat.setId(matches.get(0).getId());
			} else {
				ruat.setId(null);
				// ruat.setStatus("1");
			}
			System.out.println("estatus guardado " + ruat.getStatus());
			ruat = ruatDao.saveAndLogStatus(ruat, userModifier);// Necesita
																// llevar varios
																// estados
			ruatRegisterDTO = RuatHelperDto.convertToDto(ruat);
			return ruatRegisterDTO;
		}
		return null;
	}

	public List<RuatRegisterDTO> listUserOwners() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public RuatRegisterDTO findOne(Long id) {
		// TODO Auto-generated method stub
		Ruat ruat = ruatDao.findOne(id);
		RuatRegisterDTO ruatRegisterDTO = new RuatRegisterDTO();
		ruatRegisterDTO.setFirstName(ruat.getFirstName());
		return ruatRegisterDTO;
	}

	// public long saveAssociativity(AssociativityDTO associativityDT0) {
	// if (null != associativityDT0) {
	// List<AssociativityRegisterDTO> registers = associativityDT0
	// .getAssociativityRegisters();
	// for (AssociativityRegisterDTO register : registers) {
	// Associativity entity = AssociativityHelperDto
	// .converRegisterToEntity(register);
	// associativityDao.save(entity);
	// }
	// }
	//
	// return 1;
	// }

	@Override
	public ProcessTransferInnovationDTO getProcessTransferInnovationDTOByRuatId(
			Long ruatId) {
		ProcessTransferInnovationDTO ptDto = new ProcessTransferInnovationDTO();

		List<ProcessTransferInnovation> merchandising = processTransferInnovationDao
				.listMerchandisingByRuatId(ruatId);
		List<ProcessTransferInnovation> organizational = processTransferInnovationDao
				.listOrganizationalByRuatId(ruatId);
		List<ProcessTransferInnovation> production = processTransferInnovationDao
				.listProductionByRuatId(ruatId);
		List<ProcessTransferInnovation> transformation = processTransferInnovationDao
				.listTransformationByRuatId(ruatId);

		for (ProcessTransferInnovation pti : merchandising) {
			ProcessTransferInnovationRegisterDTO regDTO;
			regDTO = ProcessTransferInnovationHelperDto
					.convertToRegisterDTO(pti);
			ptDto.getCommercializationProcess().add(regDTO);
		}

		for (ProcessTransferInnovation pti : organizational) {
			ProcessTransferInnovationRegisterDTO regDTO;
			regDTO = ProcessTransferInnovationHelperDto
					.convertToRegisterDTO(pti);
			ptDto.getOrganizationalProcess().add(regDTO);
		}

		for (ProcessTransferInnovation pti : production) {
			ProcessTransferInnovationRegisterDTO regDTO;
			regDTO = ProcessTransferInnovationHelperDto
					.convertToRegisterDTO(pti);
			ptDto.getProductionProcess().add(regDTO);
		}

		for (ProcessTransferInnovation pti : transformation) {
			ProcessTransferInnovationRegisterDTO regDTO;
			regDTO = ProcessTransferInnovationHelperDto
					.convertToRegisterDTO(pti);
			ptDto.getTransformationProcess().add(regDTO);
		}

		return ptDto;
	}

	@Override
	public void saveProcessTransferInnovationDTO(
			ProcessTransferInnovationDTO ptiDto, String userModifier) {
		List<ProcessTransferInnovationRegisterDTO> listPtirDto = new ArrayList<ProcessTransferInnovationRegisterDTO>();

		listPtirDto.addAll(ptiDto.getCommercializationProcess());
		listPtirDto.addAll(ptiDto.getOrganizationalProcess());
		listPtirDto.addAll(ptiDto.getProductionProcess());
		listPtirDto.addAll(ptiDto.getTransformationProcess());

		List<ProcessTransferInnovation> pti = new ArrayList<ProcessTransferInnovation>();

		for (ProcessTransferInnovationRegisterDTO ptir : listPtirDto) {
			pti.add(ProcessTransferInnovationHelperDto
					.converRegisterToEntity(ptir));
		}
		processTransferInnovationDao.saveAndLog(pti, userModifier);

	}

	@Override
	public AssociativityDTO getAssociativityDTOByRuatId(Long ruatId) {
		AssociativityDTO asDTO = new AssociativityDTO();
		List<Associativity> lias = associativityDao.listByRuatId(ruatId);
		for (Associativity as : lias) {
			asDTO.getAssociativityRegisters().add(
					AssociativityHelperDto.convertToRegisterDTO(as));
		}
		return asDTO;
	}

	@Override
	public void saveAssociativityDTO(AssociativityDTO asDTO, String userModifier) {

		List<Associativity> lias = new ArrayList<Associativity>();
		for (AssociativityRegisterDTO asrDTO : asDTO
				.getAssociativityRegisters()) {
			lias.add(AssociativityHelperDto.converRegisterToEntity(asrDTO));
		}
		associativityDao.saveAndLog(lias, userModifier);

	}

	@Override
	public AgrarianResourceDTO getAgrarianResourceDTOByRuatId(Long ruatId) {

		AgrarianResourceDTO agDTO = new AgrarianResourceDTO();
		List<AgrarianResource> liar = agrarianResourceDao.listByRuatId(ruatId);
		if (liar.isEmpty()) {
			return null;
		}

		for (AgrarianResource ag : liar) {
			agDTO.getAgrarianResourceRegisters().add(
					AgrarianResourceHelperDto.convertToRegisterDTO(ag));
		}
		return agDTO;
	}

	@Override
	public void saveAgrarianResourceDTO(AgrarianResourceDTO arDTO,
			String userModifier) {
		List<AgrarianResource> ar = new ArrayList<AgrarianResource>();
		for (AgrarianResourceRegisterDTO agrDTO : arDTO
				.getAgrarianResourceRegisters()) {
			ar.add(AgrarianResourceHelperDto.converRegisterToEntity(agrDTO));
		}
		agrarianResourceDao.saveAndLog(ar, userModifier);
	}

	@Override
	public ForestResourceDTO getForestResourceDTOByRuatId(Long ruatId) {
		ForestResourceDTO foDTO = new ForestResourceDTO();
		List<ForestResource> lifo = forestResourceDao.listByRuatId(ruatId);
		if (lifo.isEmpty()) {
			return null;
		}
		for (ForestResource fo : lifo) {
			foDTO.getForestResourceRegisters().add(
					ForestResourceHelperDto.convertToRegisterDTO(fo));
		}
		return foDTO;
	}

	@Override
	public void saveForestResource(ForestResourceDTO foDTO, String userModifier) {
		List<ForestResource> lifo = new ArrayList<ForestResource>();
		for (ForestResourceRegisterDTO forDTO : foDTO
				.getForestResourceRegisters()) {
			lifo.add(ForestResourceHelperDto.converRegisterToEntity(forDTO));
		}
		forestResourceDao.saveAndLog(lifo, userModifier);
	}

	@Override
	public LivestockResourceDTO getLivestockResourceDTOByRuatId(Long ruatId) {
		LivestockResourceDTO liDTO = new LivestockResourceDTO();
		List<LivestockResource> lili = livestockResourceDao
				.listByRuatId(ruatId);

		if (lili.isEmpty()) {
			return null;
		}

		for (LivestockResource li : lili) {
			liDTO.getLivestockResourceRegisters().add(
					LivestockResourceHelperDto.convertToRegisterDTO(li));
		}
		return liDTO;
	}

	@Override
	public void saveLivestockResource(LivestockResourceDTO liDTO,
			String userModifier) {
		List<LivestockResource> lifo = new ArrayList<LivestockResource>();
		for (LivestockResourceRegisterDTO lirDTO : liDTO
				.getLivestockResourceRegisters()) {
			lifo.add(LivestockResourceHelperDto.converRegisterToEntity(lirDTO));
		}
		livestockResourceDao.saveAndLog(lifo, userModifier);

	}

	@Override
	public List<RuatRegisterDTO> findRuatDtoListByParamas(Long idType,
			String idNumber, String name) {
		System.out.println("idtipe " + idType);
		System.out.println("idnumber " + idNumber);
		System.out.println("name " + name);
		List<Ruat> liRuats = ruatDao.findByIdTypeIdNumberOrName(idType,
				idNumber, name);
		List<RuatRegisterDTO> liRuatRegisterDTO = new ArrayList<RuatRegisterDTO>();
		for (Ruat ruat : liRuats) {
			System.out.println(ruat.getId());
			liRuatRegisterDTO.add(RuatHelperDto.convertToDto(ruat));
		}

		return liRuatRegisterDTO;
	}

	@Override
	public SurveyDTO getSurveyByRuatId(Long ruatId) {
		SurveyDTO suDTO;
		List<Survey> liSu = surveyDao.listByRuatId(ruatId);
		if (!liSu.isEmpty()) {
			suDTO = SurveyHelperDto.convertToDTO(liSu.get(0));
		} else {
			return null;
		}
		return suDTO;
	}

	@Override
	public void saveSurvey(SurveyDTO suDTO, String userModifier) {
		Survey su = SurveyHelperDto.converRegisterToEntity(suDTO);
		surveyDao.saveAndLog(su, userModifier);

	}

	@Override
	public void deleteRuat(Long ruatId, String userModifier) {
		Ruat ruat = ruatDao.findOne(ruatId);
		ruatDao.deleteLogicallyAndLog(ruat, userModifier);

	}

	@Override
	public Page<Ruat> load(int pageIndex, int pageSize, String sortField,
			SortOrder sortOrder, Map<String, String> filters) {
		System.out.println();
		Direction order = Sort.Direction.ASC;
		String defaultSortField = "firstLastName";
		if (sortOrder != null) {
			if (sortOrder.name().equals("ASCENDING")) {
				order = Sort.Direction.ASC;
			} else {
				order = Sort.Direction.DESC;
			}
		}
		if (sortField != null && sortField != "") {
			defaultSortField = sortField;
		}
		Pageable pageSpecification = new PageRequest(pageIndex, pageSize,
				new Sort(order, defaultSortField));

		System.out.println("Table filters : " + filters.toString());

		Page<Ruat> pageRuats = null;

		if (filters.isEmpty()) {
			pageRuats = ruatDao.findAll(pageSpecification);
		} else {
			String idNumber = NON_VALUE;
			String fullName = NON_VALUE;
			String fullLastName = NON_VALUE;
			if (filters.containsKey("idNumber")) {
				idNumber = filters.get("idNumber");
			}
			if (filters.containsKey("fullName")) {
				fullName = filters.get("fullName");
			}
			if (filters.containsKey("fullLastName")) {
				fullLastName = filters.get("fullLastName");
			}
			pageRuats = ruatDao.findAll(fullName, fullLastName, idNumber,
					pageSpecification);
		}
		return pageRuats;
	}

	@Override
	public void deleteProcessTransferInnovation(
			ProcessTransferInnovationRegisterDTO selected, String userModifier) {
		ProcessTransferInnovation pti = (ProcessTransferInnovationHelperDto
				.converRegisterToEntity(selected));
		processTransferInnovationDao.deleteLogicallyAndLog(pti, userModifier);
	}

	@Override
	public void deleteAgrarianResourceRegister(
			AgrarianResourceRegisterDTO selected, String userModifier) {
		AgrarianResource age = (AgrarianResourceHelperDto.converRegisterToEntity(selected));
		agrarianResourceDao.deleteLogicallyAndLog(age, userModifier);
	}

	@Override
	public void deleteLivestockResourceRegister(
			LivestockResourceRegisterDTO selected, String userModifier) {
		LivestockResource age = (LivestockResourceHelperDto.converRegisterToEntity(selected));
		livestockResourceDao.deleteLogicallyAndLog(age, userModifier);		
	}

	@Override
	public void deleteForestResourceRegister(
			ForestResourceRegisterDTO selected, String userModifier) {
		ForestResource age = (ForestResourceHelperDto.converRegisterToEntity(selected));
		forestResourceDao.deleteLogicallyAndLog(age, userModifier);		
		
	}

	@Override
	public Boolean registerAlreadyExisist(RuatRegisterDTO ruatRegisterDTO) {
		List<Ruat> matches = ruatDao.findByIdTypeIdNumber(ruatRegisterDTO.getIdType(), ruatRegisterDTO.getIdNumber());
		if (matches != null && !matches.isEmpty()){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public RuatRegisterDTO findOneIdTypeIdNumber(Long idType, String idNumber) {
		List<Ruat> matches = ruatDao.findByIdTypeIdNumber(idType, idNumber);
		if(!matches.isEmpty()){
			return RuatHelperDto.convertToDto(matches.get(0));
		}		
		return null;
	}

}
